#include "Game.h"
#include "Player.h"
#include "Race.h"
#include "Jet.h"
#include "Track.h"
#include "GameState.h"
#include "App.h"
#include "XML_Loader.h"
#include <macUtils.h>
#include <Foundation/NSString.h>

extern DebugTracer _DEBUGTRACER;
Game::Game(Ogre::SceneNode* root)
{
    m_root = NULL;
    m_race = NULL;
    m_player = NULL;

    m_root = root;
    m_race = new Race();

    m_state = RACING;
    m_dirty = true;

    m_player = new Player();
    m_player->SetName("frutiemax");

    static Track* track = new Track();
	
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
	NSString *documentsDirectory = [paths objectAtIndex:0]; 
	NSString *docsPath = [documentsDirectory stringByAppendingPathComponent:@"config"]; 
	
	NSFileManager *fileManager = [NSFileManager defaultManager];
	
	if(![fileManager fileExistsAtPath:docsPath]){
		std::cout << "No config path!!!" << std::endl;
		NSString *resPath = [[[NSBundle mainBundle] resourcePath]
                                         stringByAppendingPathComponent:@"config"];
		//[fileManager createDirectoryAtPath:resPath attributes:nil];
		[fileManager copyItemAtPath:resPath toPath:docsPath error:nil];
	}
	
	
    XML_Loader::LoadFromXmlFile(track,"test_track2.xml");

	static Jet* jet = new Jet(m_root, track);
   
    if(XML_Loader::LoadJetFromXmlFile(jet,"jet_list.xml","Debug"))
	{
		std::cout << "JET LOADED!!!" << std::endl;
        m_player->ChooseJet(jet);
	}else {
		std::cout << "JET NOT LOADED :(" << std::endl;
	}


    m_race->AddPlayer(m_player);

    m_race->SelectTrack(track);

    m_race->Start();

    XML_Loader::SaveTrack(track,"test_track3.xml");
}



Game::~Game()
{
    //dtor
}

void Game::Update(float timedelta)
{
	
    switch(m_state)
    {
        case RACING:
			m_race->Update(timedelta);
			break;
    }
}
void Game::OnAccelerateKey(float timedelta)
{
    m_player->GetJet()->Accelerate(DEFK_SENSITIVITY, timedelta);
}
void Game::OnTurnRightKey(float timedelta)
{
    m_player->GetJet()->Steer(DEFK_SENSITIVITY);
}
void Game::OnTurnLeftKey(float timedelta)
{
    m_player->GetJet()->Steer(DEFK_SENSITIVITY);
}
void Game::OnBrakeKey(float timedelta)
{
    m_player->GetJet()->Brake(DEFK_SENSITIVITY, timedelta);
}
void Game::OnTurnRightJoystick(float delta)
{
}
void Game::OnTurnLeftJoystick(float delta)
{
}
